package com.qinghe.pro.service.main.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qinghe.pro.entity.main.User;
import com.qinghe.pro.entity.main.UserRole;
import com.qinghe.pro.exception.ExistedException;
import com.qinghe.pro.exception.NotDeletedException;
import com.qinghe.pro.mapper.main.UserMapper;
import com.qinghe.pro.mapper.main.UserRoleMapper;
import com.qinghe.pro.service.main.UserService;

@Service("userServiceImpl")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public User findById(Integer id) {
		User user = userMapper.selectById(id);
		return user;
	}

	@Override
	public User findByUsername(String username) {
		return userMapper.selectByUsername(username);
	}

	@Override
	public void insert(User user) {
		if (userMapper.selectByUsername(user.getUsername()) != null) {
			throw new ExistedException("用户名：" + user.getUsername() + "已存在。");
		}
		if (StringUtils.isNotBlank(user.getTel()) && userMapper.selectByTel(user.getTel()) != null) {
			throw new ExistedException("手机号码：" + user.getTel() + "已存在。");
		}
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		user.setStatus(User.STATUS_ENABLED);

		userMapper.insertSelective(user);

		// 保存用户角色关系
		if (user != null && user.getUserRoles().size() > 0) {
			UserRole userRole = new UserRole();
			userRole.setUserId(user.getId());
			userRole.setRole(user.getUserRoles().get(0).getRole());
			userRoleMapper.insert(userRole);
		}
	}

	@Override
	public void update(User user) {
		if (StringUtils.isNotBlank(user.getTel()) && userMapper.selectByIdNotAndTel(user.getId(), user.getTel()) != null) {
			throw new ExistedException("手机号码：" + user.getTel() + "已存在。");
		}
		if (StringUtils.isNotBlank(user.getPassword()))
			user.setPassword(DigestUtils.md5Hex(user.getPassword()));

		userMapper.updateByPrimaryKeySelective(user);

		// 保存用户角色关系
		if (user != null && user.getUserRoles().size() > 0) {
			UserRole userRole = new UserRole();
			userRole.setId(user.getUserRoles().get(0).getId());
			userRole.setUserId(user.getId());
			userRole.setRole(user.getUserRoles().get(0).getRole());
			userRoleMapper.updateByPrimaryKey(userRole);
		}
	}

	@Override
	public void updateStatus(Integer userId, Integer status) {
		if (isSupervisor(userId) && status == User.STATUS_DISABLED) {
			throw new NotDeletedException("不能禁用超级管理员用户。");
		}
		User user = new User(userId);
		user.setStatus(status);
		userMapper.updateByPrimaryKeySelective(user);
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Integer id) {
		return id == 1;
	}

	@Override
	public void delete(Integer id) {
		if (isSupervisor(id)) {
			throw new NotDeletedException("不能删除超级管理员用户。");
		}
		userMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Map<String, Integer> countByRole() {
		List<Map<String, Object>> list = userMapper.countByRole();
		
		Map<String, Integer> countMap = new LinkedHashMap<String, Integer>();
		for (Map<String, Object> map : list) {
			countMap.put(map.get("name").toString(), Integer.valueOf(map.get("num").toString()));
		}
		return countMap;
	}

}
